package com.kuaimacode.kframework.admin.controller.login;

import com.kuaimacode.kframework.admin.services.agent.SysAgentService;
import com.kuaimacode.kframework.admin.services.feedback.FeedbackService;
import com.kuaimacode.kframework.admin.services.finance.AgentDrawApplyService;
import com.kuaimacode.kframework.admin.services.user.OrderService;
import com.kuaimacode.kframework.admin.services.user.SysAdminUserService;
import com.kuaimacode.kframework.admin.services.user.UserDrawApplyService;
import com.kuaimacode.kframework.admin.services.user.UserService;
import com.kuaimacode.kframework.admin.util.SessionUtil;
import com.kuaimacode.kframework.admin.vo.request.AdminOrderReq;
import com.kuaimacode.kframework.admin.vo.request.AgentOrderReq;
import com.kuaimacode.kframework.admin.vo.response.AgentOrderResp;
import com.kuaimacode.kframework.constants.PageConstants;
import com.kuaimacode.kframework.util.DateUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import javax.validation.Valid;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Optional;

/**
 * 用户登录
 **/
@Slf4j
@Controller
public class LoginController{

    @Autowired
    private SysAdminUserService adminUserService;
    @Autowired
    private SysAgentService agentService;
    @Autowired
    private OrderService orderService;
	@Autowired
	private UserService userService;
	@Autowired
	private AgentDrawApplyService agentDrawApplyService;
	@Autowired
	private UserDrawApplyService userDrawApplyService;
	@Autowired
	private FeedbackService feedbackService;


	@RequestMapping(value = {"/login"}, method = RequestMethod.GET)
	public String login() {
		return "login";
	}

	@RequestMapping("/index")
	public String list(ModelMap model, @Valid AdminOrderReq req,
					   @RequestParam(value = "pageNum", defaultValue = PageConstants.PAGE_NUM + "") int pageNum,
					   @RequestParam(value = "pageSize", defaultValue = PageConstants.PAGE_SIZE + "") int pageSize) {
	    model.put("openAgentCount", agentService.openAgentCount());
		//model.put("newOrders", orderService.top10Order());
        model.put("totalOrderAmount", orderService.totalOrderAmount());//交易总额
        model.put("totalUnInAmount", orderService.totalUnInAmount());//未入账
		model.put("userCount", userService.userCount(1));//用户总数
		model.put("masterCount", userService.userCount(2));//师傅总数
		model.put("partnerCount", userService.userCount(3));//合作商家总数
		model.put("userBalance", userService.totalAmount(1));//用户总余额
		model.put("masterBalance", userService.totalAmount(2));//师傅总余额
		model.put("agentBalance", agentService.totalBalance());//分站总余额

		//今日订单数量
//		model.put("todayOrderCount", orderService.todayOrderCount());
//		model.put("todayOrderAmount", orderService.todayOrderAmount());
		String today = DateUtil.dateToString(new Date(), DateUtil.LONG_DATE_FORMAT);
		model.put("todayTotalOrderCount", orderService.dayOrderCount(today, 0));//总有效订单
		model.put("todayPTOrderCount", orderService.dayOrderCount(today, 1));//跑腿订单
		model.put("todayOtherOrderCount", orderService.dayOrderCount(today, 2));//其他订单
		model.put("todayOrderAmount", orderService.dayOrderAmount(today, 0));

		//昨日订单数量
		String yesterday = DateUtil.dateSub(Calendar.DAY_OF_MONTH, -1, "yyyy-MM-dd");
		model.put("yesterdayTotalOrderCount", orderService.dayOrderCount(yesterday, 0));//总有效订单
		model.put("yesterdayPTOrderCount", orderService.dayOrderCount(yesterday, 1));//跑腿订单
		model.put("yesterdayOtherOrderCount", orderService.dayOrderCount(yesterday, 2));//其他订单
		model.put("yesterdayOrderAmount", orderService.dayOrderAmount(yesterday, 0));

		//待办任务
		model.put("agentDrawApplayCount", agentDrawApplyService.count(0));//待处理分站提现申请
		model.put("userDrawApplayCount", userDrawApplyService.count(1, 1));//待处理用户提现申请
		model.put("masterDrawApplayCount", userDrawApplyService.count(1, 2));//待处理师傅提现申请
		model.put("unDealComplain", feedbackService.count(1, 1));//待处理投诉
		model.put("unDealFeedback", feedbackService.count(2, 1));//待处理反馈

		//交易汇总
		if(req.getStartTime() == null){
        	String date = DateUtil.dateSub(Calendar.DAY_OF_MONTH, -30, "yyyy-MM-dd");
        	req.setStartTime(date);
		}
		if(req.getEndTime() == null){
			req.setEndTime(DateUtil.getNow("yyyy-MM-dd"));
		}
		AgentOrderReq aReq = new AgentOrderReq();
		BeanUtils.copyProperties(req, aReq);
		List<AgentOrderResp> list = agentService.findAgentOrderDetail(aReq, pageNum, pageSize);
		Optional.ofNullable(list).ifPresent(agentOrderResps -> agentOrderResps.forEach(AgentOrderResp::exchangeTranType));
		model.put("agentOrderList", list);
		model.put("orderReq", req);
        model.put("endTime", DateUtil.getNow(DateUtil.LONG_DATE_FORMAT));
        model.put("startTime", DateUtil.format(DateUtil.plus(DateUtil.DateEnum.MONTH, -1), DateUtil.LONG_DATE_FORMAT));

		return "index";
	}

	@RequestMapping(value = "/login", method = RequestMethod.POST)
	public String login(
			@RequestParam(value = "username", required = true) String username,
			@RequestParam(value = "password", required = true) String password,ModelMap model) {
		Subject subject = SecurityUtils.getSubject();
		UsernamePasswordToken token = new UsernamePasswordToken(username, password);
		try {
			subject.login(token);
            SessionUtil.putUserId(adminUserService.findByUserName(username).getUserId());
			return "redirect:index";
		} catch (AuthenticationException e) {
			model.put("message", "用户名密码错误");
            log.error("用户登陆失败, username: {}", username, e);
		} catch (Exception e) {
            model.put("message", "登陆失败");
            log.error("用户登陆失败, username: {}", username, e);
        }
		return "login";
	}

	@RequestMapping(value = {"/logout"}, method = RequestMethod.GET)
	public String logout() {
		Subject subject = SecurityUtils.getSubject();
		subject.logout();
		// url重定向
		return "redirect:login";
	}



}